package cn.com.yang.thread;

/**
 * @Desc<...>
 * @Author 杨亿金
 * @Date 2020/12/14 17:26
 * @CopyRight
 * @Version
 */
public class SynAddRunnable implements Runnable {
    int a, b;

    public SynAddRunnable(int a, int b) {
        this.a = a;
        this.b = b;
    }

    /**
     * 死锁的原因：Integer.valueOf()方法减少对象创建次数和节省内存的考虑
     * -128~127之间的对象进行缓存，参数在这个范围，直接返回缓存的对象
     */
    @Override
    public void run() {
        synchronized (Integer.valueOf(a)) {
            synchronized (Integer.valueOf(b)) {
                System.out.println(a + b);
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(new SynAddRunnable(1, 2)).start();
            new Thread(new SynAddRunnable(1, 2)).start();
        }
    }
}
